package com.wy.springbootblog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wy.springbootblog.mapper.UserMapper;
import com.wy.springbootblog.pojo.Result;
import com.wy.springbootblog.pojo.User;
import com.wy.springbootblog.service.UserService;
import com.wy.springbootblog.util.JwtUtil;
import com.wy.springbootblog.util.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author work
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService {

    @Autowired
    private UserMapper userMapper;
    
    // 新增一个用户
    @Override
    public boolean saveUser(User user) {
        // 1.判断用户名是否已经存在
        User queryUser = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, user.getUsername()));
        if (queryUser == null) {
            // 2.md5加密
            String md5Password = Md5Util.getMD5String(user.getPassword());
            user.setPassword(md5Password);
            user.setCreateTime(LocalDateTime.now());
            user.setUpdateTime(LocalDateTime.now());
            // 3.注册
            userMapper.insert(user);
            return true;
        } else {
            return false;
        }
    }

    // 用户登录
    @Override
    public Result login(String username, String password) {
        // 1.判断用户名是否存在
        String md5Password = Md5Util.getMD5String(password);
        User queryUser = userMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
        if (queryUser == null) {
            // 用户不存在
            return Result.error("用户名不存在");
        }
        // 2.判断密码是否正确
        if (md5Password.equals(queryUser.getPassword())) {
            // 3.颁发jwt令牌
            Map<String,Object> map = new HashMap<>();
            map.put("id", queryUser.getId());
            map.put("username", queryUser.getUsername());
            map.put("role", queryUser.getRole());
            String token = JwtUtil.genToken(map);
            return Result.success(token);
        }
        return Result.error("用户名或密码错误");
    }

}
